package com.app.project;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.Stack;
import java.util.TimerTask;
import java.util.UUID;

import com.app.DB.SegwayDetails;
import com.app.project.BESM_LoginActivity.InsertService;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;

public class BluetoothData_test extends Activity{
	
	private BluetoothDevice device;
	private static final String Name = "Bluetooth Test";
	private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private static final int MASSAGE_READ = 100;
	private ConnectThread mConnectThread = null;
	private AcceptThread mAcceptThread = null;
	private ConnectedThread mConnectedThread = null;
	private BluetoothAdapter mBluetoothAdapter = null;
	private BluetoothSocket socket = null;
	private String mDeviceName = "Admin";
	private ListView mDataView;
	private ArrayAdapter<String> mArrayAdapter;
	private StringBuilder sb = new StringBuilder();
	private String Android_Command ="";
	private static final String Balance = "B";
	private static final String Battery = "S";
	private Handler Handler = new Handler();
	
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog mProgressDialog;
	private Boolean UpdatetoServer = false;
	private static final int END = 0;
	private static final int UPDATE = 1;
	private int OPERATION ;
	private String ServiceOID ;
	
	// -------------Map----------------------//
	private LocationClient mLocationclient;
	private Location mCurrentLocation;
	private GoogleMap map;
    private LocationManager locationManager;
    private String provider;
    
    // -------------Monitor----------------------//
    EditText CarID,CarBattery,CarBalance;
    Button buttonB,buttonS,buttonClear;
    Stack<String> st = new Stack();
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_map);
		
		CarID = (EditText) findViewById(R.id.A_Main_carid);
	    CarBattery = (EditText) findViewById(R.id.A_Main_battery);
	    CarBalance = (EditText) findViewById(R.id.A_Main_Balance);
	    
		Bundle bundle = getIntent().getExtras();
		if(bundle != null){
			mDeviceName = (String) bundle.get("Device Name");
			ServiceOID = (String) bundle.get("OID");
		}
		this.setTitle("Connect Car "+ mDeviceName);
		CarID.setText(mDeviceName);
		String address = (String) bundle.get("Device Address");
		
		mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
		device = mBluetoothAdapter.getRemoteDevice(address);
//		device = mBluetoothAdapter.getRemoteDevice("20:12:05:27:01:69");
		
//		SegwayID.setText(address);
		
		if(mAcceptThread == null){
			mAcceptThread = new AcceptThread();
			mAcceptThread.start();
		}
		if(mConnectThread == null){
			mConnectThread = new ConnectThread(device);
			mConnectThread.start();
		}
		
		mArrayAdapter = new ArrayAdapter<String>(this, R.layout.databluetooth);
		mDataView = (ListView) findViewById(R.id.A_Main_listmessage);
		mDataView.setAdapter(mArrayAdapter);
			
	}
	
	public void onStart(){
		super.onStart();
		Toast.makeText(BluetoothData_test.this, "In the onStart() event",
             Toast.LENGTH_SHORT).show();
	}
	
	
	public void onStop(){
		super.onStop();
		Toast.makeText(BluetoothData_test.this, "In the onStop() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onPause(){
		super.onPause();
		Toast.makeText(BluetoothData_test.this, "In the onPause() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onRestart(){
		super.onRestart();
		Toast.makeText(BluetoothData_test.this, "In the onRestart() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onDestroy(){
		super.onDestroy();
		Toast.makeText(BluetoothData_test.this, "In the onDestroy() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onResume() {
		super.onResume();
		Toast.makeText(BluetoothData_test.this, "In the onResume() event",
	             Toast.LENGTH_SHORT).show();
		buttonB = (Button)findViewById(R.id.A_Main_buttonB);
	    buttonB.setOnClickListener(SentCommanB);
	    buttonS = (Button)findViewById(R.id.A_Main_buttonS);
	    buttonS.setOnClickListener(SentCommanS);
	    buttonClear = (Button)findViewById(R.id.A_Main_buttonClear);
	    buttonClear.setOnClickListener(Clear);
	        
		Handler.removeCallbacks(mUpdateCarBalance);
	    Handler.postDelayed(mUpdateCarBalance,5000);
	    Handler.removeCallbacks(mUpdateCarBattery);
	    Handler.postDelayed(mUpdateCarBattery, 5000);
	    Handler.removeCallbacks(mUpdate);
	    Handler.postDelayed(mUpdate, 5000);
	    
		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.Map_Map)).getMap();
        map.setMyLocationEnabled(true);
        map.setIndoorEnabled(true);
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

	}
	
	
	
	private Runnable mUpdateCarBalance = new Runnable(){

		public void run() {
			Android_Command=Balance;
			mArrayAdapter.clear();
			
			mArrayAdapter.add(st.toString());
			int a=st.size();
			if(a>5){
				
			}else{
				st.push(Android_Command);
				
			}
			Handler.postDelayed(this, 500);
		} 	
    };
    
    private Runnable mUpdate = new Runnable(){

		public void run() {
			if(st.isEmpty()){
        		
        	}else{
            	Android_Command=st.pop().toString();
            	mConnectedThread.write(Android_Command);
            	mArrayAdapter.clear();
    			mArrayAdapter.add(st.toString());
    			
        	}
			Handler.postDelayed(this, 100);
		} 	
    };
    
    private Runnable mUpdateCarBattery = new Runnable(){

		public void run() {
			Android_Command=Battery;
			mArrayAdapter.clear();
			mArrayAdapter.add(st.toString());
			int a=st.size();
			if(a>10){
				
			}else{
				st.push(Android_Command);
			}
			Handler.postDelayed(this, 10000);
			
		} 	
    };
    
	private OnClickListener SentCommanB = new OnClickListener() {
	        public void onClick(View v) {
//	        	CarSpeed.setText("");
//	        	CarBalance.setText("");
	        	Android_Command=Battery;
	        	st.push(Android_Command);
	        	mArrayAdapter.clear();
				mArrayAdapter.add(st.toString());
				 Handler.postDelayed(mUpdateCarBalance,1000);
	        }
	}; 
	private OnClickListener SentCommanS = new OnClickListener() {
        public void onClick(View v) {
//        	CarBattery.setText("");
//        	Android_Command=Battery;
//        	mConnectedThread.write(Android_Command);
//        	mArrayAdapter.add(st.toString());
        	if(st.isEmpty()){
        		
        	}else{
        		CarBattery.setText("");
            	Android_Command=st.pop().toString();
            	mConnectedThread.write(Android_Command);
//            	String AAA=st.pop().toString();
//            	CarBattery.setText(Android_Command);
            	mArrayAdapter.clear();
    			mArrayAdapter.add(st.toString());
            	
        	}
//        	
        }
	}; 
	private OnClickListener Clear = new OnClickListener() {
        public void onClick(View v) {
        	mArrayAdapter.clear();
        	CarBattery.setText("");
        	CarBalance.setText("");
        	mArrayAdapter.add(st.toString());
        }
	}; 
	
	
	private class AcceptThread extends Thread{
		private final BluetoothServerSocket mmServerSocket;
		
		public AcceptThread(){
			BluetoothServerSocket tmp = null;
			try{
				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(Name, MY_UUID);
			}catch(IOException e){
				
			}
			mmServerSocket = tmp;
		}
		
		public void run(){
			while(true){
				try{
					socket = mmServerSocket.accept();
				}catch(IOException e){
					break;
				}
				if(socket != null){
					mConnectedThread = new ConnectedThread(socket);
					mConnectedThread.start();
					try{
						mmServerSocket.close();
					}catch(IOException e){
						e.printStackTrace();
					}
					break;
				}
			}
		}
		@SuppressWarnings("unused")
		public void cancle(){
			try{
				mmServerSocket.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	private class ConnectThread extends Thread{
		private final BluetoothSocket mmSocket;
		@SuppressWarnings("unused")
		private final BluetoothDevice mmDevice;
		
		public ConnectThread(BluetoothDevice device){
			BluetoothSocket tmp = null;
			mmDevice = device;
			try{
				tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
			}catch(IOException e){
				
			}
			mmSocket = tmp;
		}
		
		public void run(){
			mBluetoothAdapter.cancelDiscovery();
			try{
				mmSocket.connect();
			}catch(IOException connectException){
				try{
					mmSocket.close();
				}catch(IOException closeException){
					
				}
				return;
				
			}
			mConnectedThread = new ConnectedThread(mmSocket);
			mConnectedThread.start();
		}
		
		@SuppressWarnings("unused")
		public void cancle(){
			try{
				mmSocket.close();
			}catch(IOException e){
				
			}
		}
	}
	
	private class ConnectedThread extends Thread{
		private final BluetoothSocket mmSocket;
		private final InputStream mmInStream;
		private final OutputStream mmOutStream;
		
		public ConnectedThread(BluetoothSocket socket){
			//Log.d("THREAD", "constructor");
			mmSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;
			try{
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			}catch(IOException e){
				
			}
			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}
		

		public void run(){
			Log.d("THREAD", "inside run" );
			byte[] buffer =new byte[256];
			int bytes;
			while (true) {
//				Log.d("in loop", "waiting for data");
				try{
					bytes = mmInStream.read(buffer);
					mHandler.obtainMessage(MASSAGE_READ, bytes, -1,buffer).sendToTarget();
//					
					//SystemClock.sleep(1000);
//					Log.d("recieve", "b " + bytes);
				}catch(IOException e){
					break;
				}
				
			}
		}
		
		public void write(String message){
			Log.d("TAG", "...Data to send: " + message + "...");
			byte[] msgBuffer = message.getBytes();
			try{
				mmOutStream.write(msgBuffer);
			}catch(IOException e){
				Log.d("TAG", "...Error data send: " + e.getMessage() + "...");  
			}
		}
		@SuppressWarnings("unused")
		public void cancle(){
			try{
				mmSocket.close();
			}catch(IOException e){
				
			}
		}
	}
	
	private final Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MASSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				String strIncom = new String(readBuf, 0, msg.arg1);
				mArrayAdapter.add("Arduino : "+strIncom.toString());
				sb.append(strIncom);												// append string
            	int endOfLineIndex = sb.indexOf("\r\n");							// determine the end-of-line
            	if (endOfLineIndex > 0) { 											// if end-of-line,
            		String sbprint = sb.substring(0, endOfLineIndex);				// extract string
                    sb.delete(0, sb.length());
                    if(Android_Command.equals(Battery)){
                    	CarBattery.setText(sbprint); 
                    }else if(Android_Command.equals(Balance)){
                    	CarBalance.setText(sbprint); 
                    }
                }
     
                break;
                
			}
			
		}
	};
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }
	
	//-----------InsertService-Loading----------------------------------//
    public class InsertService extends AsyncTask<String, Void, Void> {
        @SuppressWarnings("deprecation")
		protected void onPreExecute() {
        	super.onPreExecute();
        	showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
        	
        	switch (OPERATION){
        		case END:
        			SegwayDetails usr = new SegwayDetails(
        					ServiceOID,
                			null,
                			null,
            				"1",
            				null,	
            				null,
            				null,
            				null,
            				null,
            				null,
            				null,
            				null,
            				null,
            				null
            		);
            		try {
        				if(usr.OperationData("End") != null){
        					UpdatetoServer = true;
        				}
        			} catch (Exception e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        			break;
        			
        		case UPDATE:
        			
        			break;
        		default:
    	            return null;
        	}
        	
    		return null;
        }

        @SuppressWarnings("deprecation")
		protected void onPostExecute(Void unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            removeDialog(DIALOG_DOWNLOAD_PROGRESS);
            if(UpdatetoServer){
            	
            }
        	
        }
        
    }
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
	
	
	 @Override
		public void onBackPressed() {
		  
		        new AlertDialog.Builder(this)
		        .setTitle("ออกจากโปรแกรม")
		        .setMessage("ต้องการออกจากโปรแกรม")
		                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

		                    @SuppressWarnings("deprecation")
							public void onClick(DialogInterface arg0, int arg1) {
		                    	Intent intent = new Intent(BluetoothData_test.this,BESM_LoginActivity.class);
		                    	startActivity(intent);
		                    	Handler.removeCallbacks(mUpdateCarBalance);
		                    	Handler.removeCallbacks(mUpdateCarBattery);
		                    	Handler.removeCallbacks(mUpdate);
		                    	if(mAcceptThread != null){
		                			mAcceptThread.cancle();
		                		}
		                		if(mConnectThread != null){
		                			mConnectThread.cancle();
		                		}
		                		OPERATION=END;
		                		new  InsertService().execute();
		                        finish();
		                    }
		                })
		                .setPositiveButton(android.R.string.no, new DialogInterface.OnClickListener() {

		                    public void onClick(DialogInterface arg0, int arg1) {
		                    	
		                    }
		                }).create().show();
		} 
	 
	 
	 	
		
}
